from flask import Flask, request, Response, stream_with_context, jsonify
import requests
from flask_cors import cross_origin

app = Flask(__name__)

@app.route('/proxy', methods=['POST', 'OPTIONS'])
@cross_origin(supports_credentials=True, origins=['http://127.0.0.1:5501'], methods=['POST', 'OPTIONS'])
def proxy():
    if request.method == 'OPTIONS':
        # 预检请求直接返回200 OK
        return '', 200

    url = "https://spark-api-open.xf-yun.com/v1/chat/completions"
    
    # 获取请求头中的Authorization信息
    headers = {
        "Authorization": request.headers.get("Authorization"),
        "Content-Type": "application/json",
    }
    
    # 将原始请求体转发给目标API
    req_body = request.get_json()

    try:
        # 发起请求到目标API，并将响应流式返回给客户端
        response = requests.post(url, headers=headers, json=req_body, stream=True)

        def generate():
            for chunk in response.iter_content(chunk_size=None, decode_unicode=False):
                if chunk:
                    try:
                        # 解码每个块为UTF-8字符串
                        decoded_chunk = chunk.decode('utf-8')
                        print(f"Decoded chunk: {decoded_chunk}")  # 打印调试信息
                        yield f"data: {decoded_chunk}\n\n"
                    except UnicodeDecodeError as e:
                        print(f"UnicodeDecodeError: {e}")
                        # 如果解码失败，尝试忽略错误字符
                        decoded_chunk = chunk.decode('utf-8', errors='replace')
                        yield f"data: {decoded_chunk}\n\n"

        return Response(stream_with_context(generate()), content_type='text/event-stream')

    except requests.exceptions.RequestException as e:
        # 处理请求异常
        error_message = {"error": str(e)}
        return jsonify(error_message), 500

if __name__ == '__main__':
    app.run(port=3000)